<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { Card, Table, Tag, MessagePlugin, Button, Dialog, Form, Input, Select, Textarea, Tooltip } from 'tdesign-vue-next';
import { TimeIcon } from 'tdesign-icons-vue-next';
import { getAllDevLogs, addDevLog } from '@/api/devlog/devLog';
import EllipsisTooltip from '@/components/EllipsisTooltip.vue';

const logs = ref([]);
const addVisible = ref(false);
const addLoading = ref(false);
const addForm = ref({
  version: '',
  changeType: undefined,
  module: '',
  category: undefined,
  title: '',
  content: '',
  logTime: '',
});
const addRules = {
  version: [{ required: true, message: '请输入版本号', type: 'error' }],
  changeType: [{ required: true, message: '请选择变更类型', type: 'error' }],
  module: [{ required: true, message: '请输入模块', type: 'error' }],
  category: [{ required: true, message: '请选择类别', type: 'error' }],
  title: [{ required: true, message: '请输入标题', type: 'error' }],
  logTime: [{ required: true, message: '请选择时间', type: 'error' }],
};

const columns = [
  { colKey: 'version', title: '版本号', align: 'left' as const },
  { colKey: 'changeType', title: '变更类型', align: 'center' as const },
  { colKey: 'module', title: '模块', align: 'center' as const },
  { colKey: 'category', title: '类别', align: 'center' as const },
  { colKey: 'content', title: '内容', align: 'left' as const, ellipsis: true, minWidth: 220 },
  { colKey: 'logTime', title: '时间', align: 'center' as const, minWidth: 140 },
];

const changeTypeMap = { 1: '新增', 2: '优化', 3: '修复', 4: '重构', 5: '删除' };
const changeTypeTheme = { 1: 'primary', 2: 'success', 3: 'danger', 4: 'warning', 5: 'danger' };
const categoryMap = { 0: '前端', 1: '后端' };

const fetchLogs = async () => {
  try {
    const res = await getAllDevLogs();
    if (res.data && res.data.code === 200) {
      logs.value = res.data.data || [];
    } else {
      MessagePlugin.error(res.data?.message || '获取开发日志失败');
    }
  } catch (e) {
    MessagePlugin.error('获取开发日志异常');
  }
};

onMounted(fetchLogs);

const handleAdd = () => {
  addForm.value = {
    version: '',
    changeType: undefined,
    module: '',
    category: undefined,
    title: '',
    content: '',
    logTime: '',
  };
  addVisible.value = true;
};

const handleAddSubmit = async () => {
  addLoading.value = true;
  try {
    const submitData = { ...addForm.value };
    if (submitData.logTime && typeof submitData.logTime === 'string') {
      submitData.logTime = submitData.logTime.replace(' ', 'T');
    }
    const res = await addDevLog(submitData);
    if (res.data && res.data.code === 200) {
      MessagePlugin.success('新增成功');
      addVisible.value = false;
      await fetchLogs();
    } else {
      MessagePlugin.error(res.data?.message || '新增失败');
    }
  } catch (e) {
    MessagePlugin.error('新增异常');
  } finally {
    addLoading.value = false;
  }
};

function isOverflow(el) {
  if (!el) return false;
  return el.scrollWidth > el.clientWidth;
}

function useEllipsisTooltip() {
  const overflowMap = ref({});
  const setRef = (id, el) => {
    if (el) {
      nextTick(() => {
        overflowMap.value[id] = isOverflow(el);
      });
    }
  };
  return { overflowMap, setRef };
}

const { overflowMap: titleOverflowMap, setRef: setTitleRef } = useEllipsisTooltip();
const { overflowMap: contentOverflowMap, setRef: setContentRef } = useEllipsisTooltip();
</script>

<template>
  <Card class="dev-logs-card" bordered>
    <div class="dev-logs-header">
      <TimeIcon class="dev-logs-header-icon" />
      <span class="dev-logs-title">开发日志</span>
      <t-button v-throttle="handleAdd" theme="primary" style="margin-left:auto">新增开发日志</t-button>
    </div>
    <div class="dev-logs-scroll">
      <Table
        row-key="id"
        :data="logs"
        :columns="columns"
        hover
        size="medium"
        class="dev-logs-table"
        ellipsis
        :header-cell-style="{ background: '#fff', color: 'var(--td-text-color-primary)', fontWeight: 400 }"
        table-layout="auto"
        max-height="600px"
      >
        <template #changeType="{ row }">
          <Tag :theme="changeTypeTheme[row.changeType] || 'default'" variant="light-outline">
            {{ changeTypeMap[row.changeType] || row.changeType }}
          </Tag>
        </template>
        <template #module="{ row }">
          <span class="dev-logs-module">
            {{ row.module }}
          </span>
        </template>
        <template #category="{ row }">
          <Tag
            v-if="row.category === 0"
            class="tag-frontend"
            variant="light-outline"
          >
            {{ categoryMap[row.category] || row.category }}
          </Tag>
          <Tag
            v-else
            :color="'#2db7f5'"
            variant="light-outline"
            class="tag-backend"
          >
            {{ categoryMap[row.category] || row.category }}
          </Tag>
        </template>
        <template #logTime="{ row }">
          <span class="dev-logs-date">
            {{ row.logTime ? row.logTime.replace('T', ' ') : '' }}
          </span>
        </template>
        <template #content="{ row }">
          <div class="dev-logs-content-cell" style="max-width:500px;width:500px;min-width:500px;overflow:hidden;">
            <div class="dev-logs-content-title" style="max-width:500px;width:500px;min-width:500px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;">
              <EllipsisTooltip
                :text="row.title"
                className="ellipsis"
                style="display:inline-block;max-width:100%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;"
              />
            </div>
            <ul v-if="row.content">
              <li
                v-for="(item, idx) in row.content.split(/\r?\n|；|;|。/).filter(Boolean)"
                :key="idx"
                class="dev-logs-content-line"
                style="max-width:500px;width:500px;min-width:500px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"
              >
                <EllipsisTooltip
                  :text="item.trim()"
                  className="ellipsis"
                  style="display:inline-block;max-width:100%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;"
                />
              </li>
            </ul>
          </div>
        </template>
      </Table>
    </div>
    <t-dialog v-model:visible="addVisible" header="新增开发日志" :confirm-btn="{ content: '保存', loading: addLoading }" cancel-btn="取消" @confirm="handleAddSubmit">
      <t-form :data="addForm" :rules="addRules" label-align="right" layout="vertical" label-width="120px">
        <t-form-item label="版本号" name="version">
          <t-input v-debounce.input="onInputVersion" v-model="addForm.version" placeholder="请输入版本号" style="width:240px" />
        </t-form-item>
        <t-form-item label="变更类型" name="changeType">
          <t-select v-model="addForm.changeType" :options="[
            { label: '新增', value: 1 },
            { label: '优化', value: 2 },
            { label: '修复', value: 3 },
            { label: '重构', value: 4 },
            { label: '删除', value: 5 },
          ]" placeholder="请选择变更类型" style="width:240px" />
        </t-form-item>
        <t-form-item label="模块" name="module">
          <t-input v-debounce.input="onInputModule" v-model="addForm.module" placeholder="如：用户模块、权限模块" style="width:240px" />
        </t-form-item>
        <t-form-item label="类别" name="category">
          <t-select v-model="addForm.category" :options="[
            { label: '前端', value: 0 },
            { label: '后端', value: 1 },
          ]" placeholder="请选择类别" style="width:240px" />
        </t-form-item>
        <t-form-item label="标题" name="title">
          <t-input v-debounce.input="onInputTitle" v-model="addForm.title" placeholder="请输入标题" style="width:240px" />
        </t-form-item>
        <t-form-item label="正文内容" name="content">
          <t-textarea v-model="addForm.content" placeholder="每行一个要点，支持分点展示" rows="4" style="width:240px" />
        </t-form-item>
        <t-form-item label="时间" name="logTime">
          <t-date-picker v-model="addForm.logTime" enable-time-picker format="YYYY-MM-DD HH:mm:ss" placeholder="请选择时间" style="width:260px" />
        </t-form-item>
      </t-form>
    </t-dialog>
  </Card>
</template>

<style lang="less" scoped>
.dev-logs-card {
  background: var(--td-bg-color-container, #fff);
  margin: 24px 8px;
  padding: 24px;
  min-height: 80vh;
}
.dev-logs-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}
.dev-logs-header-icon {
  font-size: 22px;
  color: var(--td-brand-color);
  margin-right: 10px;
}
.dev-logs-title {
  font-size: 22px;
  font-weight: 600;
  color: var(--td-text-color-primary);
}
.dev-logs-scroll {
  position: relative;
  height: 600px;
  overflow-y: auto;
}
.dev-logs-table {
  margin-bottom: 0;
}
.dev-logs-version {
  color: var(--td-brand-color);
  font-weight: bold;
  font-size: 16px;
}
.dev-logs-module {
  font-size: 14px;
  color: var(--td-text-color-primary);
}
.dev-logs-content-cell {
  display: flex;
  flex-direction: column;
  gap: 2px;
}
.dev-logs-content-title {
  font-size: 16px;
  color: var(--td-text-color-primary);
  margin-bottom: 2px;
}
.dev-logs-content-list {
  margin: 0;
  padding-left: 18px;
}
.dev-logs-content-line {
  font-size: 14px;
  color: var(--td-text-color-secondary);
  margin-left: 0;
  list-style-type: decimal;
}
.dev-logs-date {
  font-size: 14px;
  color: #666;
}

.tag-frontend {
  background-color: #f3eafe !important;
  color: #8e63ff !important;
  border: 1px solid #8e63ff !important;
}
[theme-mode='dark'] .tag-frontend {
  background-color: #1b2f51 !important;
  color: #8e63ff !important;
  border: 1px solid #8e63ff !important;
}

.tag-backend {
  background-color: #eaf8ff !important;
  color: #2db7f5 !important;
  border: 1px solid #2db7f5 !important;
}
[theme-mode='dark'] .tag-backend {
  background-color: #1b2f51 !important;
  color: #2db7f5 !important;
  border: 1px solid #2db7f5 !important;
}
</style>